package com.csjbot.blackgaga.feature.settings;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.csjbot.blackgaga.BuildConfig;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.base.BaseFullScreenActivity;
import com.csjbot.blackgaga.base.BasePresenter;
import com.csjbot.blackgaga.dialog.ProgressDialog;
import com.csjbot.blackgaga.model.http.ApiUrl;
import com.csjbot.blackgaga.util.AndroidCopyVersion;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.DownloadUtil;
import com.csjbot.blackgaga.widget.NewRetailDialog;
import com.csjbot.cameraclient.utils.CameraLogger;
import com.csjbot.coshandler.log.Csjlogger;

import org.json.JSONObject;

import java.io.File;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xiasuhuei321 on 2017/10/20.
 * author:luo
 * e-mail:xiasuhuei321@163.com
 */

public class SettingsCheckUpdateActivity extends BaseFullScreenActivity {

    @BindView(R.id.tv_system_version)
    TextView mTvSystemVersion;
    @BindView(R.id.tv_version_number)
    TextView mTvVersionNumber;//版本号
    @BindView(R.id.tv_updateInfo)
    TextView mTvUpdateInfo;//更新内容
    @BindView(R.id.bt_update)
    Button mBtUpdate;
    private String NewRetail = null;
    //当前版本
    private int presentVersionCode;
    //远程版本
    private int version_code = -1;
    // 下载安装包的网络路径
    private String apkUrl;
    // 保存apk的文件夹
    private static final String savePath = "/sdcard/Download/";
    //保存的apk名称
    private static final String saveFileName = savePath + "newRetail.apk";
    private ProgressDialog downloadDialog;// 下载对话框
    // 通知处理刷新界面的handler
    private String mVersion_name;
    private String md5;
    AndroidCopyVersion androidCopyVersion = new AndroidCopyVersion(this);
    private DownloadUtil downloadUtil;

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_check_update;
    }

    @Override
    public boolean isOpenTitle() {
        return true;
    }

    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        getTitleView().setSettingsVisibility(View.GONE);
        getTitleView().setSettingsPageBackVisibility(View.VISIBLE);
        presentVersionCode = getVersionCode(getApplication());
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mTvVersionNumber.setText(androidCopyVersion.getVersion());

    }

    private void initData() {
        new Thread(() -> {
            try {
                resolveJson();
                downloadUtil.getRemoteFileLength();
            } catch (Exception e) {
                CameraLogger.debug("e" + e.toString());
                e.printStackTrace();
            }
        }).start();

    }


    //获取版本号
    public static int getVersionCode(Context context) {
        //包管理器
        PackageManager packageManager = context.getPackageManager();
        String packageName = context.getPackageName();

        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            int versionCode = packageInfo.versionCode;
            return versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 1;
    }

    @OnClick(R.id.bt_update)
    public void onViewClicked() {
        if (version_code > presentVersionCode) {
            File apkfile = new File(saveFileName);
            if (!apkfile.exists()) {
                showNoticeDialog();
                //            } else {
                //                String fileMD5 = MD5.getFileMD5(saveFileName + savePath);
                //                String md5 = SharedPreUtil.getString(SharedKey.APK_INFO, SharedKey.APK_MD5, "null");
                //                // 校验 apk md5
                //                new Thread(() -> {
                //                    if (md5.equals(fileMD5)) {
                //                        runOnUiThread(this::installApk);
                //                    } else {
                //                        runOnUiThread(() -> {
                //                            BlackgagaLogger.debug("md5不一致，重新下载apk");
                //                            apkfile.delete();
                //                            showNoticeDialog();
                //                        });
                //
                //                    }
                //                }).start();
            }
        } else if (version_code == -1) {
            Toast.makeText(this, R.string.Please_check_network, Toast.LENGTH_SHORT).show();
            Csjlogger.debug("version_code--->" + version_code);

        } else {
            Toast.makeText(this, R.string.already_latest_version, Toast.LENGTH_SHORT).show();
        }
    }

    private void resolveJson() throws Exception {
        if (BuildConfig.robotType.equals(BuildConfig.ROBOT_TYPE_DEF_ALICE)) {
            NewRetail = "NewRetail_alies";
        } else if (BuildConfig.robotType.equals(BuildConfig.ROBOT_TYPE_DEF_SNOW)) {
            NewRetail = "NewRetail_snow";
        }
        Csjlogger.debug("robotType---" + BuildConfig.robotType);
        String url = ApiUrl.DEFAULT_ADRESS + "api/tms/versionRobot?category=" + NewRetail + "&channel=standard";//版本更新
        Csjlogger.debug("url---" + url);
        OkHttpClient okHttpClient_get = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().get()
                .url(url)
                .build();
        Response response;
        response = okHttpClient_get.newCall(request).execute();
        String json = response.body().string();
        CameraLogger.debug("---" + json);
        JSONObject jsonObject = new JSONObject(json);
        JSONObject scoreObj = (JSONObject) jsonObject.get("result");
        JSONObject obj = (JSONObject) scoreObj.get("resule");
        //版本号
        version_code = obj.getInt("version_code");
        //更新地址
        apkUrl = obj.getString("url");
        //版本类型
        String channel = obj.getString("channel");
        //版本名
        mVersion_name = obj.getString("version_name");
        //机器人类型
        String category = obj.getString("category");
        // md5
        md5 = obj.getString("checksum");

        // 2.进行版本号比对
        int versionCode = getVersionCode(SettingsCheckUpdateActivity.this);
        CameraLogger.debug("---获取的数据是: 机器人类型:" + category + "  服务器版本号:" + version_code + "  " +
                " 当前版本" + versionCode + "  更新地址:" + apkUrl + "  版本类型:" + channel + "  版本名:" + mVersion_name);
        //        mTvSystemVersion.post(() -> mTvSystemVersion.setText(getString(R.string.current_version) + mVersion_name));

    }

    private void showNoticeDialog() {
        showNewRetailDialog(getString(R.string.version_update), mVersion_name, getString(R.string.apk_download), getString(R.string.update_later), new NewRetailDialog.OnDialogClickListener() {
            @Override
            public void yes() {
                showDownloadDialog();
                dismissNewRetailDialog();
            }

            @Override
            public void no() {
                dismissNewRetailDialog();
            }
        });
    }

    public void showDownloadDialog() {
        downloadDialog = new ProgressDialog(this);
        downloadDialog.setTitle(getString(R.string.version_update));
        downloadDialog.setListener(() -> {
            downloadDialog.dismiss();
            /*手动取消下载,删除文件*/
            DownloadUtil.isCanceled = true;
        });
        downloadDialog.show();
        downloadDialog.setCancelable(false);
        downloadDialog.setOnKeyListener(keylistener);
        downloadApk();
    }

    private void downloadApk() {
        downloadUtil = new DownloadUtil(1, "http://" + apkUrl, savePath);
        downloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
            @Override
            public void onSuccess(int downloadId) {
                installApk();
                BlackgagaLogger.debug(downloadId + "下载成功");
                downloadDialog.dismiss();
            }

            @Override
            public void onStart(int downloadId, long fileSize) {
                long localFileLength = downloadUtil.getLocalFileLength();
                if (localFileLength == fileSize) {
                    installApk();
                    downloadDialog.dismiss();
                    return;
                }

                BlackgagaLogger.debug("localFileLength--开始下载-----：" + localFileLength);
                BlackgagaLogger.debug(downloadId + "开始下载，文件大小-------：" + fileSize);


            }

            @Override
            public void onPublish(int downloadId, long size) {
                BlackgagaLogger.debug("更新文件----------111111111111---------->" + size);
                /*进度条*/
                downloadDialog.getProgressId().setProgress((int) size);
            }

            @Override
            public void onPause(int downloadId) {
                BlackgagaLogger.debug("暂停下载" + downloadId);
            }

            @Override
            public void onGoon(int downloadId, long localSize) {
                BlackgagaLogger.debug("继续下载" + downloadId + "----" + localSize);


            }

            @Override
            public void onError(int downloadId) {
                BlackgagaLogger.debug("下载出错" + downloadId);
                Toast.makeText(SettingsCheckUpdateActivity.this, R.string.download_fail, Toast.LENGTH_SHORT).show();
                downloadDialog.dismiss();

            }

            @Override
            public void onCancel(int downloadId) {
                BlackgagaLogger.debug("取消下载" + downloadId);
                DownloadUtil.isCanceled = false;
                downloadDialog.dismiss();
            }
        });

        downloadUtil.start(false);

    }

    ProgressDialog.OnKeyListener keylistener = (dialog, keyCode, event) -> {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            DownloadUtil.isCanceled = true;
            downloadDialog.setCancelable(false);
            Csjlogger.debug("返回键按了-false--");
            return false;
        } else {
            Csjlogger.debug("返回键按了-true--");
            return true;
        }
    };

    protected void installApk() {
        File apkfile = new File(savePath + downloadUtil.getFileName());
        BlackgagaLogger.debug("在安装------>");
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");// File.toString()会返回路径信息
        SettingsCheckUpdateActivity.this.startActivity(i);
        BlackgagaLogger.debug("---apkfile" + apkfile.toString());
    }
}
